<template>
  <div>
      <div class="bottom-loading-tip" v-show="loading">加载中…</div>
      <div class="bottom-loading-tip" v-show="allLoaded">加载完成</div>
  </div>
</template>
<script>
export default {
  name: 'LoadMore',
  async created(){
    //   await this.toBottom()
    this.open()
  },
  data(){
      return {
          loading: false
      }
  },
  computed:{
      listener(){
          return this.toBottom.bind(this)
      }
  },
  methods:{
      async toBottom(){
        const scrollTop = window.scrollY,
            pageHeight = window.innerHeight,
            scrollHeight = document.body.scrollHeight;
        // 避免页面由过长突然变成一页时触发的事件
        // 好奇怪 按理说在一页时 scrollTop和scrollHeight此时都应该为0的 但是在这个瞬间
        // scrollTop为0 scrollHeight为页面长度 稍后变为0
        if(!scrollTop) return
        if (scrollTop + pageHeight > scrollHeight - 5) {
            console.log('到底了')
            if(this.loading) return
            this.loading = true
            // 避免重复调用bottomMethod
            await this.bottomMethod()
            this.loading = false
        }
      },
      open(){
          window.addEventListener('scroll', this.listener, false)
      },
      close(){
          window.removeEventListener('scroll', this.listener, false)
      }
  },
  watch:{
    //全部内容加载完成后 停止监听。反之继续监听。   
      allLoaded(value){
          if(!value) this.open()
          else {
              this.loading = false
              this.close()
            }
      }
  },
  beforeDestroy(){
      this.close()
  },
    // bottomMethod为到底部方法，allLoaded为true后不仅会停止监听 还会自动显示'加载完成'字样
  props: ['bottomMethod', 'allLoaded']
}
</script>

